﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using Tesla.Graphics.Implementation;

namespace Tesla.Direct3D10.Graphics {
    /// <summary>
    /// ResourceTracker tracks all implementations created by the D3D10 render system in order to ensure all
    /// slimdx objects are disposed of. Objects disposed by the user will inform the tracker that that object
    /// should no longer be tracked.
    /// </summary>
    internal sealed class ResourceTracker {

        private Object _syncObject;
        private Dictionary<IntPtr, ResourceData> _resources;
        private D3D10Renderer _parent;

        public ResourceTracker(D3D10Renderer renderer) {
            _parent = renderer;
            _syncObject = new Object();
            _resources = new Dictionary<IntPtr, ResourceData>();
        }

        public void AddTrackedObject(IntPtr pointer, GraphicsResourceImplementation impl) {
            lock(_syncObject) {
                ResourceData data;
                if(_resources.TryGetValue(pointer, out data)) {
                    //If get same pointer, consider the old resource to have been disposed of
                    data.Pointer = pointer;
                    data.ManagedObject = new WeakReference(impl);
                    _resources[pointer] = data;
                } else {
                    data.Pointer = pointer;
                    data.ManagedObject = new WeakReference(impl);
                    _resources.Add(pointer, data);
                }
            }
        }

        public bool Contains(IntPtr pointer) {
            lock(_syncObject) {
                return _resources.ContainsKey(pointer);
            }
        }

        public GraphicsResourceImplementation GetManagedObject(IntPtr pointer) {
            lock(_syncObject) {
                ResourceData data;
                if(_resources.TryGetValue(pointer, out data)) {
                    if(data.ManagedObject.IsAlive) {
                        return (GraphicsResourceImplementation) data.ManagedObject.Target;
                    }
                }
                return null;
            }
        }


        public void RemoveTrackedObject(IntPtr pointer) {
            lock(_syncObject) {
                _resources.Remove(pointer);
            }
        }

        public void ReleaseAllResources() {
            lock(_syncObject) {
                IntPtr[] keys = new IntPtr[_resources.Keys.Count];
                _resources.Keys.CopyTo(keys, 0);
                foreach(IntPtr key in keys) {
                    ResourceData data;
                    if(_resources.TryGetValue(key, out data)) {
                        if(data.ManagedObject.IsAlive) {
                            GraphicsResourceImplementation target = data.ManagedObject.Target as GraphicsResourceImplementation;
                            if(target != null && !target.IsDisposed) {
                                target.Dispose();
                            }
                        }
                    }
                }
                _resources.Clear();
            }
        }
    }

    internal struct ResourceData {
        public IntPtr Pointer;
        public WeakReference ManagedObject;
    }
}
